using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using LispInterpretor.HelperClasses;

namespace LispInterpretor.Parsers
{
    public class IfStatementParser : IParser
    {
        #region IParser Members

        public bool Is(string text, Environment environment)
        {
            string lowerCase = text.ToLower();

            return lowerCase.StartsWith("(if ") && lowerCase.EndsWith(")");
        }

        public object Evaluate(string text, Environment environment)
        {
            bool predicate = EvaluatePredicate(text, environment);

            if (predicate)
            {
                return EvalConsequent(text, environment);
            }
            else
            {
                return EvalAlternative(text, environment);
            }
        }

        private bool EvaluatePredicate(string text, Environment environment)
        {
            object result =  Evaluator.Eval(ParserHelper.ParseArguments(text, 1), environment);

            Check.IsTrue(result is bool, "Predicate does not evaluate to a boolean.");

            return (bool)result;
         }

      
        private object EvalAlternative(string text, Environment environment)
        {
            return Evaluator.Eval(ParserHelper.ParseArguments(text, 3), environment);
        }

        private object EvalConsequent(string text, Environment environment)
        {
            return Evaluator.Eval(ParserHelper.ParseArguments(text, 2), environment);
        }

        #endregion
    }
}
